package com.example.shopp_2301.login

import android.os.Bundle
import android.text.InputType
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.shopp_2301.R
import com.example.shopp_2301.databinding.ActivityLoginBinding

@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    var flag = false//密码默认可见
    override fun initView() {
        binding.btnLogin.setOnClickListener {
            val phone = binding.etPbone.text.toString()
            val pwd = binding.etPwd.text.toString()
            if(phone.isEmpty()||pwd.isEmpty()){
                ToastUtils.showLong("用户名和密码均不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(phone)){
                ToastUtils.showLong("手机号格式不正确")
                return@setOnClickListener
            }
            if(!RegexUtils.isMatch("^[\\w]{6,18}$",pwd)){
                ToastUtils.showLong("密码格式不正确，应该为数字、字母、下划线组合")
                return@setOnClickListener
            }
            if(!binding.cb.isChecked){
                ToastUtils.showLong("请先勾选同意协议")
                return@setOnClickListener
            }
            viewModel.login(phone,pwd)
        }
        //点击文字跳转到对应页面 （结束当前页面）
        binding.goLoginCode.setOnClickListener {
            finish()
            ARouter.getInstance().build("/app/LoginCodeActivity").navigation()
        }
        //点击小眼睛，密码修改可见不可见
        binding.ivEye.setOnClickListener{
            if(flag==true){//不可见状态
                //修改成可见的
                binding.etPwd.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                flag = false
            }else{
                binding.etPwd.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                flag = true
            }
        }

    }

    override fun initData() {
        viewModel.loginSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                SPUtils.getInstance().put("phone",it.data.phone)
                finish()
                ARouter.getInstance().build("/app/ShopActivity").navigation()
            }
        }
        viewModel.loginFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun getViewModel(): Class<LoginViewModel> {
       return LoginViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.activity_login
    }

}